package edu.java.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

import edu.java.ishop.model.UserRole;
import edu.java.ishop.services.UserService;

public class LoginServlet extends HttpServlet {

	private UserService userService;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		if(username != null && password != null){
			UserRole principal = userService.getPrincipal(username, password);
			
			if(principal != null){
				
				req.getSession().setAttribute("ISHOP_PRINCIPAL", principal);
				//resp.sendRedirect("main");
				resp.sendRedirect("product/list.do");
				return;
			}
		}
		
		resp.sendRedirect("login.jsp?error=invalidLoginPassword");
	}
	@Override
	public void init() throws ServletException {
		userService = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean(UserService.class);
	}
}
